package com.lmb.util;

import cn.hutool.crypto.digest.DigestUtil;

public class PasswordUtil {
    private final static char[] arr={'a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9'};
    private final static int salt_index=5;//索引
    private final static int count_index=15;
    public static String getEncryption(String password){//密码加密
        //随机盐值
        int index_salt=(int)(Math.random()*arr.length);
        char salt=arr[index_salt];
        //随机加密次数
        int index_count=(int)(Math.random()*10);
        char count=arr[index_count];
        String encryptionPassword=password+salt;//加盐
        for (int i = 0; i < count; i++){
            encryptionPassword=DigestUtil.md5Hex(encryptionPassword);//md5加密
        }
        StringBuilder strb=new StringBuilder(encryptionPassword);//创建一个可变字符串
        strb.insert(salt_index,salt);//插入盐值和加密次数
        strb.insert(count_index,count);
        return strb.toString();//返回加密后的密码
    }

    public static boolean checkPassword(String password,String encryptionPassword){//密码校验
        //盐值
        char salt=encryptionPassword.charAt(salt_index);//获取盐值
        //加密次数
        char count=encryptionPassword.charAt(count_index);//获取加密次数
        String decode=password+salt;
        for (int i = 0; i < count; i++){
            decode=DigestUtil.md5Hex(decode);//md5加密
        }
        StringBuilder strb=new StringBuilder(decode);//创建一个可变字符串
        strb.insert(salt_index,salt);//插入盐值和加密次数
        strb.insert(count_index,count);
        //返回校验结果
        return strb.toString().equals(encryptionPassword);
    }

    public static void main(String[] args) {
//        System.out.println(getEncryption("123456"));
//        System.out.println(checkPassword("123456","01717e47cca0ac4a60d2d261041c4841a4"));
    }
}